package com.lhd.qd.module.system.user.model.converter;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lhd.qd.module.system.user.model.dto.UserSaveDTO;
import com.lhd.qd.module.system.user.model.vo.UserCacheVO;
import com.lhd.qd.module.system.user.model.vo.UserDetailVO;
import com.lhd.qd.module.system.user.model.vo.UserInfoVO;
import com.lhd.qd.module.system.user.model.vo.UserListVO;
import com.lhd.qd.module.system.user.model.dataobj.UserDO;
import com.lhd.qd.module.system.user.model.dto.UserInfoDTO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;

import java.util.HashMap;
import java.util.Map;

@Mapper
public abstract class AbstractUserConverter {

    public static AbstractUserConverter INSTANCE = Mappers.getMapper(AbstractUserConverter.class);

    public abstract Page<UserListVO> doPage2ListVOPage(IPage<UserDO> doPage);

    public abstract UserDetailVO do2DetailVO(UserDO dataObj);

    public abstract UserDO saveDTO2DO(UserSaveDTO saveDTO);

    public abstract UserInfoVO infoDTO2InfoVO(UserInfoDTO dto);

    public Map<String, Object> infoDTO2Map(UserInfoDTO dto, String[] permissions) {

        if ( dto == null ) {
            return null;
        }

        Map<String, Object> map = new HashMap<>();
        map.put("username", dto.getUsername());
        map.put("name", dto.getName());
        map.put("hospitalId", dto.getHospitalId());
        map.put("deptId", dto.getDeptId());
        map.put("roleId", dto.getRoleId());
        map.put("permissions", permissions);

        return map;
    }

    public UserCacheVO map2CacheVO(Map<Object, Object> map) {

        if (map == null) {
            return null;
        }

        UserCacheVO userCacheVO = new UserCacheVO();

        userCacheVO.setUsername(obj2String(map.get("username")));
        userCacheVO.setName(obj2String(map.get("name")));
        userCacheVO.setHospitalId(obj2Long(map.get("hospitalId")));
        userCacheVO.setDeptId(obj2Long(map.get("deptId")));
        userCacheVO.setRoleId(obj2Long(map.get("roleId")));
        userCacheVO.setPermissions(obj2StringArray(map.get("permissions")));

        return userCacheVO;
    }

    private String obj2String(Object obj) {
        return obj == null ? null : obj.toString();
    }

    private Long obj2Long(Object obj) {
        return obj == null ? null : Long.parseLong(obj.toString());
    }

    private String[] obj2StringArray(Object obj) {
        return obj == null ? null : (String[]) obj;
    }
}
